package com.yxhl.zoume.core.tripsmgmt.ui.fragment.home;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.zoume.R;
import com.yxhl.zoume.account.event.UserLoginEvent;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.func.appraisal.model.AppraisalDriverInfo;
import com.yxhl.zoume.core.func.appraisal.model.CommentOnDriverEvent;
import com.yxhl.zoume.core.tripsmgmt.presenter.home.HistoryTripPresenter;
import com.yxhl.zoume.core.tripsmgmt.ui.adapter.HistoryTripsAdapter;
import com.yxhl.zoume.core.tripsmgmt.ui.event.HistoryTripsItemClickEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.event.JumpCommentEvent;
import com.yxhl.zoume.core.tripsmgmt.view.home.HistoryTripsView;
import com.yxhl.zoume.di.component.trip.DaggerTripComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.di.module.trip.TripModule;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * 项目名称：Ferrari
 * Created by menggod on 16/11/29 .
 * 历史行程列表
 */
public class HistoryTripsFragment extends BaseFragment implements HistoryTripsView,
        BaseQuickAdapter.RequestLoadMoreListener,
        SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "HistoryTripsFrag";

    //widgets
    @BindView(R.id.srl_include_refresh_layout)
    protected SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_include_recycler_view)
    protected RecyclerView mRecyclerView;

    @BindView(R.id.iv_include_refresh_no_record)
    protected ImageView mNoRecordIv;

    //arguments
    protected List<BizOrder> mDataList;
    private boolean isRefreshCleanList = false;

    //arguments
    @Inject
    HistoryTripPresenter mHistoryTripsPresenter;

    private HistoryTripsAdapter mHistoryTripsAdapter;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LOG.e(TAG, "onCreate");
        onRxBusEvent();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LOG.e(TAG, "onCreateView savedInstanceState=" + savedInstanceState);
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mHistoryTripsPresenter.attachView(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initAdapter();
        initSwipeRefresh();
        initRecycleView();
//        loadHistoryTripData();
    }

    @Override
    public void onStart() {
        super.onStart();
        LOG.e(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        mHistoryTripsPresenter.onResume();
        LOG.e(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        mHistoryTripsPresenter.onPause();
        LOG.e(TAG, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        LOG.e(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        LOG.e(TAG, "onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        LOG.e(TAG, "onDestroy");
        mHistoryTripsPresenter.onDestroy();
        super.onDestroy();
    }

    public HistoryTripsFragment() {
        // Required empty public constructor
    }

    private void onRxBusEvent() {

        getSubscription().add(toSubscription(HistoryTripsItemClickEvent.class,
                new Action1<HistoryTripsItemClickEvent>() {
                    @Override
                    public void call(HistoryTripsItemClickEvent historyTripsItemClickEvent) {
                        View shareView = historyTripsItemClickEvent.getShareView();
                        BizOrder bizOrder = historyTripsItemClickEvent.getBizOrder();

                        getAppComponent().navigator()
                                .navigateToDetailTripContainerActivity(mActivity, shareView, bizOrder);
                    }
                }
        ));
        getSubscription().add(toSubscription(
                UserLoginEvent.class,
                new Action1<UserLoginEvent>() {
                    @Override
                    public void call(UserLoginEvent userLoginEvent) {
                        loadHistoryTripData();
                    }
                }
        ));
        getSubscription().add(toSubscription(
                CommentOnDriverEvent.class,
                new Action1<CommentOnDriverEvent>() {
                    @Override
                    public void call(CommentOnDriverEvent commentOnDriverEvent) {
                        loadHistoryTripData();
                    }
                }
        ));
        getSubscription().add(toSubscription(JumpCommentEvent.class, new Action1<JumpCommentEvent>() {
            @Override
            public void call(JumpCommentEvent jumpCommentEvent) {
                AppraisalDriverInfo driverInfo = jumpCommentEvent.getDriverInfo();
                if (null != driverInfo) {
                    getAppComponent().navigator().navigateToAppraisal(mActivity, driverInfo);
                }
            }
        }));

    }

    public static HistoryTripsFragment newInstance() {
        HistoryTripsFragment tripsMgmtFragment = new HistoryTripsFragment();
        return tripsMgmtFragment;
    }


    /**
     * 测试
     */
    private void initSwipeRefresh() {
        mSwipeRefreshLayout.setColorSchemeResources(
                R.color.bg_color_orange,
                R.color.bg_color_green,
                R.color.colorAccent);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    private void initAdapter() {
        if (mDataList == null) {
            mDataList = new ArrayList<>();
        } else {
            mDataList.clear();
        }
        mHistoryTripsAdapter = new HistoryTripsAdapter(mDataList);
        mHistoryTripsAdapter.setOnLoadMoreListener(this);
        int size = mHistoryTripsAdapter.getData().size();
        if (size == 0) {
            mNoRecordIv.setVisibility(View.VISIBLE);
        } else {
            mNoRecordIv.setVisibility(View.INVISIBLE);
        }
    }

    private void initRecycleView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mHistoryTripsAdapter);
    }


    /**
     * 网络请求,加载历史行程数据
     */
    private void loadHistoryTripData( ) {

        if (mSwipeRefreshLayout != null) {
            if (!mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(true);
                LOG.e(TAG, "loadCurrentTripsData");
                if (mDataList == null) {
                    mDataList = new ArrayList<>();
                } else {
                    mDataList.clear();
                }
                mHistoryTripsPresenter.queryHistoryTripsData(true);
            }
        }
    }
    /**
     * 在Viewpager里,每次切换Pager,调用此方法,下拉刷新
     *
     * @param isVisibleToUser true,表示切换到当前可见的fragment时
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LOG.e(TAG, "setUserVisibleHint isVisibleToUser=" + isVisibleToUser);
            loadHistoryTripData();
        }
    }

    @Override
    public void renderDataOnSuccess(List<BizOrder> orderList) {

        if (isRefreshCleanList) {
            mDataList.clear();
            isRefreshCleanList = false;
            PromptUtils.showShort(mActivity, "刷新完成");
        }

        mDataList.addAll(orderList);
        mHistoryTripsAdapter.setNewData(mDataList);
        int size = mHistoryTripsAdapter.getData().size();
        if (size == 0) {
            mNoRecordIv.setVisibility(View.VISIBLE);
        } else {
            mNoRecordIv.setVisibility(View.INVISIBLE);
        }
        if (orderList.size() < 10) {
            mHistoryTripsAdapter.loadMoreEnd();
        } else {
            mHistoryTripsAdapter.loadMoreComplete();
        }
        resetViewControlStatus();
        stopRefresh();
    }

    @Override
    public void renderDataOnFailure(String errorMessage) {
        mHistoryTripsAdapter.loadMoreFail();
        resetViewControlStatus();
        PromptUtils.showShort(mActivity, errorMessage);
    }

    @Override
    public void renderDataOnError() {
        resetViewControlStatus();
    }

    @Override
    public void closeDownRefresh() {
        stopRefresh();
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_history_trips;
    }

    @Override
    protected void setupToolBar() {
    }

    @Override
    protected void initializeInjector() {
        DaggerTripComponent.builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(mActivity))
                .tripModule(new TripModule())
                .build()
                .inject(this);
    }


    @Override
    public void onRefresh() {
        setViewControlIsRefresh(true);
        isRefreshCleanList = true;
        startRefresh();
        if (mHistoryTripsPresenter != null) {
            LOG.e(TAG, "loadHistoryTripData");
            mHistoryTripsPresenter.queryHistoryTripsData(true);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        if (mHistoryTripsPresenter != null) {
            LOG.e(TAG, "loadHistoryTripData");
            mHistoryTripsPresenter.queryHistoryTripsData(false);
        }
    }

    private void setViewControlIsRefresh(boolean isRefresh) {
        if (isRefresh) {
            mHistoryTripsAdapter.setEnableLoadMore(false);
            mSwipeRefreshLayout.setEnabled(true);
        } else {
            mHistoryTripsAdapter.setEnableLoadMore(true);
            mSwipeRefreshLayout.setEnabled(false);
        }
    }


    private void resetViewControlStatus() {
        mHistoryTripsAdapter.setEnableLoadMore(true);
        mSwipeRefreshLayout.setEnabled(true);
        stopRefresh();
    }

    private void startRefresh() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    }

    private void stopRefresh() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }
}
